package com.metadata_system.api.inspect;

import com.metadata_system.api.annotations.ImageVerifiyCode;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.exception.ApiException;
import com.metadata_system.common.service.ImageVerifyCodeService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Configuration
@Slf4j
public class ImageVerifiyCodeAspect {
    @Autowired
    ImageVerifyCodeService imageVerifyCodeService;

    @Around("@annotation(com.metadata_system.api.annotations.ImageVerifiyCode)")
    public Object interceptor(ProceedingJoinPoint point) {
        String errorMessage="图片验证码错误";
        try {
            // 1.获取 request
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();

            // 2.获取 注解定义事件类型
            MethodSignature signature = (MethodSignature) point.getSignature();
            ImageVerifiyCode imageVerifiyCode=signature.getMethod().getAnnotation(ImageVerifiyCode.class);


            // 3.校验 图片验证码
            String imageVerifyCode = ServletRequestUtils.getStringParameter(request, "imageVerifyCode", "");
            ApiResult apiResult = this.imageVerifyCodeService.check(request.getHeader("DeviceId"), imageVerifiyCode.eventType(), imageVerifyCode);

            if (apiResult.getCode() > 0) {
                errorMessage=apiResult.getMessage();
                throw new ApiException(errorMessage);
            }
            return point.proceed();
        } catch (Throwable throwable) {
//            log.info("异常 --------"+throwable.getMessage());
            throwable.printStackTrace();
            throw new ApiException(throwable.getMessage());
        }
    }
}
